package com.exrobot.module.rbt.service.robotbox;

import com.exrobot.module.rbt.controller.admin.order.vo.OrderSaleVO;
import com.exrobot.module.rbt.controller.admin.robotbox.vo.RobotBoxDispatchVO;
import com.exrobot.module.rbt.controller.admin.robotbox.vo.RobotBoxFoodVO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Validated
public class RobotBoxDispatchServiceImpl implements RobotBoxDispatchService {

    /**
     * 检查单个车辆是否能满足订单需求
     */
    private boolean canSingleVehicleSatisfy(RobotBoxFoodVO boxFoodVO, OrderSaleVO order) {
        for (Map.Entry<Long, Integer> item : order.getItems().entrySet()) {
            Long itemId = item.getKey();
            int required = item.getValue();
            // 车辆库存不足或无此物品
            if (!boxFoodVO.getInventory().containsKey(itemId) || boxFoodVO.getInventory().get(itemId) < required) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查车辆组合是否能满足订单需求
     */
    private boolean canVehiclesCombinationSatisfy(List<RobotBoxFoodVO> boxFoodVOs, OrderSaleVO order) {
        // 计算组合的总库存
        Map<Long, Integer> totalInventory = new HashMap<>();
        for (RobotBoxFoodVO v : boxFoodVOs) {
            for (Map.Entry<Long, Integer> item : v.getInventory().entrySet()) {
                totalInventory.put(item.getKey(),
                        totalInventory.getOrDefault(item.getKey(), 0) + item.getValue());
            }
        }
        // 检查是否满足订单
        for (Map.Entry<Long, Integer> item : order.getItems().entrySet()) {
            Long itemId = item.getKey();
            int required = item.getValue();
            if (totalInventory.getOrDefault(itemId, 0) < required) {
                return false;
            }
        }
        return true;
    }

    /**
     * 调度核心逻辑：忽略距离，优先选择最少车辆
     */
    public RobotBoxDispatchVO optimizeDispatch(List<RobotBoxFoodVO> boxFoodVOs, OrderSaleVO order) {
        // 步骤1：筛选能单独满足订单的车辆（优先单车辆）
        List<RobotBoxFoodVO> singleCandidates = boxFoodVOs.stream()
                .filter(v -> canSingleVehicleSatisfy(v, order))
                .collect(Collectors.toList());

        if (!singleCandidates.isEmpty()) {
            // 不考虑距离，返回第一个满足条件的车辆（或按ID排序后返回）
            RobotBoxFoodVO bestSingle = singleCandidates.stream()
                    .findFirst()
                    .get();
            return new RobotBoxDispatchVO()
                    .setFeasible(true)
                    .setSelectedRobot(Collections.singletonList(bestSingle))
                    .setMessage("最优方案：单车辆配送（ID：" + bestSingle.getSn() + "");
        }

        // 步骤2：单车辆无法满足，尝试双车辆组合
        List<List<RobotBoxFoodVO>> twoRobotBoxCombinations = new ArrayList<>();
        for (int i = 0; i < boxFoodVOs.size(); i++) {
            for (int j = i + 1; j < boxFoodVOs.size(); j++) {
                List<RobotBoxFoodVO> combo = Arrays.asList(boxFoodVOs.get(i), boxFoodVOs.get(j));
                if (canVehiclesCombinationSatisfy(combo, order)) {
                    twoRobotBoxCombinations.add(combo);
                }
            }
        }

        if (!twoRobotBoxCombinations.isEmpty()) {
            // 不考虑距离，返回第一个满足条件的双车辆组合（或按ID排序）
            List<RobotBoxFoodVO> bestCombo = twoRobotBoxCombinations.get(0);
            String vehicleIds = bestCombo.stream()
                    .map(v -> v.getSn())
                    .collect(Collectors.joining(","));
            return new RobotBoxDispatchVO()
                    .setFeasible(true)
                    .setSelectedRobot(bestCombo)
                    .setMessage("最优方案：双车辆组合配送（IDs：" + vehicleIds + "）");
        }

        // 步骤3：尝试三车辆组合（可扩展到更多车辆）
        List<List<RobotBoxFoodVO>> threeVehicleCombinations = new ArrayList<>();
        for (int i = 0; i < boxFoodVOs.size(); i++) {
            for (int j = i + 1; j < boxFoodVOs.size(); j++) {
                for (int k = j + 1; k < boxFoodVOs.size(); k++) {
                    List<RobotBoxFoodVO> combo = Arrays.asList(boxFoodVOs.get(i), boxFoodVOs.get(j), boxFoodVOs.get(k));
                    if (canVehiclesCombinationSatisfy(combo, order)) {
                        threeVehicleCombinations.add(combo);
                    }
                }
            }
        }

        if (!threeVehicleCombinations.isEmpty()) {
            List<RobotBoxFoodVO> bestCombo = threeVehicleCombinations.get(0);
            String vehicleIds = bestCombo.stream()
                    .map(v -> v.getSn())
                    .collect(Collectors.joining(","));
            return new RobotBoxDispatchVO()
                    .setFeasible(true)
                    .setSelectedRobot(bestCombo)
                    .setMessage("最优方案：三车辆组合配送（IDs：" + vehicleIds + "）");
        }
        return new RobotBoxDispatchVO()
                .setFeasible(false)
                .setSelectedRobot(Collections.emptyList())
                .setMessage("无法满足订单需求：所有车辆库存不足");
    }
}
